package test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author tongchen
 * @create 2023-02-18 11:36
 */
public class UDPdicServer {
    //创建字典
    private HashMap<String,String>dic;
    //创建socket
   private DatagramSocket socket;
    //通过构造方法进行对所需内容的初始化

    public UDPdicServer(int port) throws SocketException {
        //创建新的hashmap
        this.dic=new HashMap<>();
        dic.put("tiger", "老虎");
        dic.put("cat", "小猫");
        dic.put("dog", "小狗");
        dic.put("pig", "小猪");
        //创建新的socket
        socket=new DatagramSocket(port);
    }

    //创建启动方法
    public void start() throws IOException {
        System.out.println("服务端启动.......");
        //创建循环
        while(true){
            //创建接收请求的packet
            DatagramPacket requestPacket=new DatagramPacket(new byte[1024],1024);
            //接收数据
            socket.receive(requestPacket);
            //对数据进行解析
            String request=new String(requestPacket.getData(), 0, requestPacket.getLength(), "utf-8");
            //根据请求获取响应
            String response=pocess(request);
            //封装数据
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8), response.getBytes().length, requestPacket.getSocketAddress());
            //发送数据
            socket.send(responsePacket);
            //打印结果
            System.out.printf("[%s:%d] request = %s, response = %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }

    }

    private String pocess(String request) {
        return dic.getOrDefault(request, "查无此词");
    }

    public static void main(String[] args) throws IOException {
        //创建服务端
        UDPdicServer udPdicServer = new UDPdicServer(9091);
        udPdicServer.start();
    }
}
